package top.leyi.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.leyi.entity.token.JwtToken;
import top.leyi.entity.user.User;
import top.leyi.mapper.UserMapper;
import top.leyi.utils.JWTUtil;

import java.util.List;


public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;
    //// 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("验证验证");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        JwtToken token = (JwtToken) principalCollection.getPrimaryPrincipal();
        User user = JWTUtil.parseJWTToUser(String.valueOf(token.getPrincipal()));

        List<String> authors = userMapper.queryOwnPrivilege(user);
        authors.forEach((e)->{
            simpleAuthorizationInfo.addStringPermission(e);
        });
        return simpleAuthorizationInfo;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token!=null;
    }

    //// 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        JwtToken jwtToken = (JwtToken) authcToken;

        User user0 = JWTUtil.parseJWTToUser(String.valueOf(jwtToken.getPrincipal()));


        User user = userMapper.queryOneUser(53);
        System.out.println(user.getToken());
        System.out.println(jwtToken.getCredentials());
         if(user == null){
             return null;
         }

        AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(jwtToken, jwtToken.getPrincipal(), this.getName());

        //清除权限缓存
        //super.clearCachedAuthorizationInfo(authcInfo.getPrincipals());
        //SecurityUtils.getSubject().getSession().setAttribute("user", user);

        return authcInfo;
    }
}
